package com.app.couponsharelife.ui.main.shop.hotsell

import android.content.Intent
import android.graphics.Paint
import android.graphics.drawable.AnimationDrawable
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.app.couponsharelife.R
import com.app.couponsharelife.base.LazyFragment
import com.app.couponsharelife.data.bean.*
import com.app.couponsharelife.data.remote.retrofit.RetrofitWorker
import com.app.couponsharelife.data.remote.retrofit.exception.OtherException
import com.app.couponsharelife.ui.main.home.good.GoodDetailActivity
import com.app.couponsharelife.utils.DataUtils
import com.scwang.smartrefresh.layout.api.RefreshFooter
import com.scwang.smartrefresh.layout.api.RefreshHeader
import com.scwang.smartrefresh.layout.api.RefreshLayout
import com.scwang.smartrefresh.layout.constant.RefreshState
import com.scwang.smartrefresh.layout.listener.OnMultiPurposeListener
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.observers.DisposableObserver
import io.reactivex.schedulers.Schedulers
import kotlinx.android.synthetic.main.base_refresh_head.*
import kotlinx.android.synthetic.main.fragment_daylong_hotsell.*
import kotlinx.android.synthetic.main.good_list_item.view.*
import java.text.DecimalFormat

/**
 *Created by xct on 2019/4/29
 *Description:24小时热销商品列表页面
 */
class DaylongHotSellFragment:LazyFragment() {
    private var homeClassBean: HomeClassBean?=null
    private var animationDrawable:AnimationDrawable?=null
    private var pageIndex=1
    private var classID=""
    private var goodsList= arrayListOf<TaobaoGoodBean>()
    private var adapter:MyAdapter?=null
    companion object {
        fun newInstance(homeClassBean: HomeClassBean): DaylongHotSellFragment {
            val fragment = DaylongHotSellFragment()
            val bundle= Bundle()
            bundle.putParcelable("Data",homeClassBean)
            fragment.arguments =bundle
            return fragment
        }
    }
    override val viewLayoutId: Int
        get() = R.layout.fragment_daylong_hotsell

    override fun initViews() {
        homeClassBean=arguments!!.getParcelable("Data")
        if (homeClassBean!=null){
            classID=(homeClassBean!!.id?:0).toString()
            setRefresh()
            fragment_dayLong_rv.layoutManager=LinearLayoutManager(context)
            adapter=MyAdapter()
            fragment_dayLong_rv.adapter=adapter
        }
    }

    override fun lazyLoad() {
        getGoodsList(false)
    }
    private fun setRefresh(){
        hotsale_refreshimg.setImageResource(R.drawable.anim_refresh)
        animationDrawable=hotsale_refreshimg.drawable as AnimationDrawable
        fragment_dayLong_smartrefresh.setOnMultiPurposeListener(object : OnMultiPurposeListener {
            override fun onFooterMoving(footer: RefreshFooter?, isDragging: Boolean, percent: Float, offset: Int, footerHeight: Int, maxDragHeight: Int) {

            }

            override fun onHeaderStartAnimator(header: RefreshHeader?, headerHeight: Int, maxDragHeight: Int) {
                //animationDrawable!!.start()
            }

            override fun onFooterReleased(footer: RefreshFooter?, footerHeight: Int, maxDragHeight: Int) {

            }

            override fun onStateChanged(refreshLayout: RefreshLayout, oldState: RefreshState, newState: RefreshState) {

            }

            override fun onHeaderMoving(header: RefreshHeader?, isDragging: Boolean, percent: Float, offset: Int, headerHeight: Int, maxDragHeight: Int) {
                setAnima(percent)
            }

            override fun onFooterFinish(footer: RefreshFooter?, success: Boolean) {

            }

            override fun onFooterStartAnimator(footer: RefreshFooter?, footerHeight: Int, maxDragHeight: Int) {

            }

            override fun onHeaderReleased(header: RefreshHeader?, headerHeight: Int, maxDragHeight: Int) {
                animationDrawable!!.start()
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                getGoodsList(false)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                pageIndex=1
                getGoodsList(true)
            }

            override fun onHeaderFinish(header: RefreshHeader?, success: Boolean) {
                hotsale_refreshimg.setImageResource(R.drawable.refresh_0)
                animationDrawable!!.stop()
            }
        })
    }
    private fun setAnima(vlaue:Float){
        val layoutParams=hotsale_refreshimg.layoutParams as ConstraintLayout.LayoutParams
        layoutParams.matchConstraintPercentHeight=vlaue/2
        layoutParams.dimensionRatio="0.875:1"
        hotsale_refreshimg.layoutParams=layoutParams
    }
    private fun setIntent(taobaoGoodBean:TaobaoGoodBean){
        val intent = Intent(context, GoodDetailActivity::class.java)
        intent.putExtra("good", taobaoGoodBean)
        startActivity(intent)
    }
    private fun getGoodsList(isRefresh:Boolean){
        if (!isRefresh&&pageIndex==1){
            showProgressDialog("加载中...")
        }
        val map=HashMap<String,String>()
        map["minId"]=pageIndex.toString()
        map["back"]="10"
        map["cid"]=classID
        RetrofitWorker.retrofitWorker.getDayLongHotSell(map)
                .subscribeOn(Schedulers.io())
                .map { DataUtils().hdkData(it) }
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : DisposableObserver<RemoteResultBean<HDKGoodsBean>>(){
                    override fun onComplete() {

                    }

                    override fun onNext(it: RemoteResultBean<HDKGoodsBean>) {
                        if (!isRefresh&&pageIndex==1){
                            dismissProgressDialog()
                        }
                        if (it.data!=null&&it.data!!.datas.isNotEmpty()){
                            if (pageIndex==1){
                                goodsList.clear()
                                if (isRefresh){
                                    fragment_dayLong_llerror.visibility= View.GONE
                                    fragment_dayLong_rv.visibility= View.VISIBLE
                                    fragment_dayLong_smartrefresh.finishRefresh()
                                }
                            }else{
                                fragment_dayLong_smartrefresh.finishLoadMore()
                            }
                            goodsList.addAll(it.data!!.datas!!)
                            if (it.data!!.datas!!.size<10){
                                fragment_dayLong_smartrefresh.finishLoadMoreWithNoMoreData()
                            }
                            pageIndex++
                            adapter!!.notifyDataSetChanged()
                        }else{
                            if (isRefresh){
                                fragment_dayLong_smartrefresh.finishRefresh()
                            }
                            if (pageIndex==1&&goodsList.size==0){
                                fragment_dayLong_smartrefresh.finishLoadMoreWithNoMoreData()
                                fragment_dayLong_llerror.visibility= View.VISIBLE
                                fragment_dayLong_rv.visibility= View.GONE
                            }
                        }
                    }

                    override fun onError(e: Throwable) {
                        if (!isRefresh&&pageIndex==1){
                            dismissProgressDialog()
                        }
                        if (isRefresh){
                            fragment_dayLong_smartrefresh.finishRefresh()
                        }
                        if (pageIndex>1){
                            fragment_dayLong_smartrefresh.finishLoadMore()
                        }
                        if (pageIndex==1){
                            fragment_dayLong_smartrefresh.finishLoadMoreWithNoMoreData()
                            fragment_dayLong_llerror.visibility= View.VISIBLE
                            fragment_dayLong_rv.visibility= View.GONE
                        }
                        if (e is OtherException){
                            showToastMsg(e.msg)
                        }else{
                            showToastMsg("网络加载出错了！")
                            //Log.e("eeee","----->"+e.toString())
                        }
                    }

                })
    }
    private inner class MyAdapter:RecyclerView.Adapter<RecyclerView.ViewHolder>(){
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
            val view= LayoutInflater.from(parent.context).inflate(R.layout.good_list_item, parent, false)
            return MyHolder(view)
        }

        override fun getItemCount(): Int {
            return goodsList.size
        }

        override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
            if (goodsList.isNotEmpty()){
                if (holder is MyHolder){
                    val good=goodsList[position]
                    val df = DecimalFormat("#0.00")
                    Glide.with(holder.itemView).asBitmap()
                            .apply(RequestOptions()
                                    .placeholder(R.drawable.ic_good_place_holder).error(R.drawable.ic_good_place_holder))
                            .load(good.pict_url)
                            .into(holder.goodsImag!!)
                    holder.goodsTitle!!.text =good.title
                    //holder.goods.setImageResource(good.userType)
                    holder.goodsXLNumber!!.text = good.volume
                    holder.goodsPrice!!.text = df.format(good.final_price.toDouble())
                    holder.goodsFL!!.text = String.format("约返¥%s", df.format(good.vip_commission.toDouble()))
                    holder.goodsOldPriceType!!.text=good.goodsSource+"价"
                    holder.goodsOldPrice!!.text=good.original_price
                    holder.goodsDayXLNumber!!.text=good.todaysale
                    holder.goodsOldPrice!!.paint.flags= Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG
                    if (0==position){
                        holder.goodsBDType!!.visibility=View.VISIBLE
                        holder.goodsBDType!!.setImageResource(R.drawable.imag_hotsell_bd1)
                    }else if(1==position){
                        holder.goodsBDType!!.visibility=View.VISIBLE
                        holder.goodsBDType!!.setImageResource(R.drawable.imag_hotsell_bd2)
                    }else if(2==position){
                        holder.goodsBDType!!.visibility=View.VISIBLE
                        holder.goodsBDType!!.setImageResource(R.drawable.imag_hotsell_bd3)
                    }else{
                        holder.goodsBDType!!.visibility=View.INVISIBLE
                    }
                    if (good.has_coupon) {
                        holder.goodsYHQPrice!!.text = String.format("¥%s", good.coupon_price)
                        holder.goodsYHQBG!!.visibility = View.VISIBLE
                    } else {
                        holder.goodsYHQBG!!.visibility = View.GONE
                    }
                    holder.itemView.setOnClickListener {
                        setIntent(good)
                    }
                }
            }
        }

    }
    private inner class MyHolder(itemView:View):RecyclerView.ViewHolder(itemView){
        var goodsImag:ImageView?=null
        var goodsBDType:ImageView?=null
        var goodsTitle:TextView?=null
        var goodsPrice:TextView?=null
        var goodsOldPrice:TextView?=null
        var goodsOldPriceType:TextView?=null
        var goodsFL:TextView?=null
        var goodsYHQPrice:TextView?=null
        var goodsXLNumber:TextView?=null
        var goodsDayXLNumber:TextView?=null
        var goodsYHQBG:LinearLayout?=null
        init {
            goodsImag=itemView.ivGoodImage
            goodsBDType=itemView.ivGoodsBD
            goodsTitle=itemView.tvGoodName
            goodsPrice=itemView.tvGoodPrice
            goodsOldPrice=itemView.tvGoodSvipProfit
            goodsOldPriceType=itemView.tvGoodtype
            goodsFL=itemView.tvGoodVipProfit
            goodsYHQPrice=itemView.tvCouponAmount
            goodsXLNumber=itemView.tvGoodVolume
            goodsDayXLNumber=itemView.tvDaySellNumber
            goodsYHQBG=itemView.choiceness_rvitm_llq1
        }
    }
}